package com.yangrd.airship.sys.web.config;

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.Formatter;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * description: WebConfigurer
 *
 * @author: yangrd
 * @date: 2021/2/5
 * @version: 1.0
 */
@Configuration
public class WebConfigurer implements WebMvcConfigurer {


    @Bean
    public Formatter<LocalDate> localDateTimeFormatter() {
        return new Formatter<LocalDate>() {

            /**
             * 解析参数
             *
             * @param text    传入日期字符串参数
             * @param locale  地区
             * @return 解析后的日期
             */
            @Override
            public LocalDate parse(String text, Locale locale) {
                return LocalDate.parse(text, DateTimeFormatter.ofPattern("yyyy-MM-dd", locale));
            }

            /**
             * 这个暂时不知道怎么使用, 也不知道干什么的...
             *
             * @param object 日期
             * @param locale 地区
             * @return 输出字符串
             */
            @Override
            public String print(LocalDate object, Locale locale) {
                return DateTimeFormatter.ISO_LOCAL_DATE.format(object);
            }
        };
    }

    @Bean
    public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {

        return (factory -> {
            ErrorPage errorPage404 = new ErrorPage(HttpStatus.NOT_FOUND, "/index.html");
            factory.addErrorPages( errorPage404);
        });
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 可添加多个
        registry.addInterceptor(new LogHandlerInterceptor()).addPathPatterns("/**");
    }
}
